package com.lanyan.system.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanyan.common.enums.RegisterStatusEnum;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.system.domain.AccountCoupon;
import com.lanyan.system.domain.vo.RegisterStatus;
import com.lanyan.system.mapper.AccountCouponMapper;
import com.lanyan.system.mapper.CouponMapper;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lanyan.common.annotation.Log;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.enums.BusinessType;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import com.lanyan.system.domain.Coupon;
import com.lanyan.system.service.ICouponService;
import com.lanyan.common.utils.poi.ExcelUtil;
import com.lanyan.common.core.page.TableDataInfo;

/**
 * 优惠券Controller
 *
 * @author lanyan
 * @date 2024-11-26
 */
@RestController
@RequestMapping("/system/coupon")
public class CouponController extends BaseController
{
    @Autowired
    private ICouponService couponService;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private AccountCouponMapper accountCouponMapper;

    /**
     * 查询优惠券列表
     */
/*    @PreAuthorize("@ss.hasPermi('system:coupon:list')")*/
    @GetMapping("/list")
    @ApiImplicitParams({
          @ApiImplicitParam(name = "createBy", value = "创建者", dataType = "String", dataTypeClass = String.class),
          @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "Date", dataTypeClass = Date.class),
          @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "Date", dataTypeClass = Date.class),
          @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "Date", dataTypeClass = Date.class),
          @ApiImplicitParam(name = "updateBy", value = "更新者", dataType = "String", dataTypeClass = String.class),
          @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "Date", dataTypeClass = Date.class),
          @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", dataTypeClass = String.class),
          @ApiImplicitParam(name = "name", value = "优惠券名称", dataType = "String", dataTypeClass = String.class),
          @ApiImplicitParam(name = "need", value = "满足金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
          @ApiImplicitParam(name = "derate", value = "优惠金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
          @ApiImplicitParam(name = "timer", value = "有效期", dataType = "String", dataTypeClass = String.class),
          @ApiImplicitParam(name = "pageNum", value = "第几页", dataType = "int", dataTypeClass = int.class),
          @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", dataTypeClass = int.class),

    })
    public TableDataInfo list(Coupon coupon)
    {
        startPage();
        List<Coupon> list = couponService.selectCouponList(coupon);

        for (Coupon coupon1 : list) {
            //查询每条优惠卷使用人数、领取、待使用、已失效梳理
            // 查询每条优惠券总领取人数
            Integer totalReceived = accountCouponMapper.selectCount(new LambdaQueryWrapper<AccountCoupon>()
                    .eq(AccountCoupon::getCouponId, coupon1.getCouponId())
                    .eq(AccountCoupon::getDelFlag, "0"));
            coupon1.setReceiveNumber(totalReceived);
            // 查询每条优惠券失效数量（已过期）
            Integer expiredCount = accountCouponMapper.selectCount(new LambdaQueryWrapper<AccountCoupon>()
                    .eq(AccountCoupon::getCouponId, coupon1.getCouponId())
                    .eq(AccountCoupon::getState, "2")
                    .eq(AccountCoupon::getDelFlag, "0"));
            coupon1.setExpiredQuantity(expiredCount);
            //查询每条优惠卷的待使用数量
            Integer toDoNumber = accountCouponMapper.selectCount(new LambdaQueryWrapper<AccountCoupon>()
                    .eq(AccountCoupon::getCouponId, coupon1.getCouponId())
                    .eq(AccountCoupon::getState, "0")
                    .eq(AccountCoupon::getDelFlag, "0"));
            coupon1.setToBeUsedNumber(toDoNumber);
            //使用数量
            LambdaQueryWrapper<AccountCoupon> accountCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
            accountCouponLambdaQueryWrapper
                    .eq(AccountCoupon::getCouponId, coupon1.getCouponId())
                    .eq(AccountCoupon::getState, "1")
                    .eq(AccountCoupon::getDelFlag, "0");
            if (StringUtils.isNotEmpty(coupon.getStartTime()) && StringUtils.isNotEmpty(coupon.getEndTime())){
                accountCouponLambdaQueryWrapper.between(AccountCoupon::getUpdateTime, coupon.getStartTime(), coupon.getEndTime());
            }
            Integer useCount = accountCouponMapper.selectCount(accountCouponLambdaQueryWrapper);
            coupon1.setUseNumber(useCount);
        }
        return getDataTable(list);
    }

    /**
     * 导出优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('system:coupon:export')")
    @Log(title = "优惠券", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Coupon coupon)
    {
        List<Coupon> list = couponService.selectCouponList(coupon);
        ExcelUtil<Coupon> util = new ExcelUtil<Coupon>(Coupon.class);
        util.exportExcel(response, list, "优惠券数据");
    }

    /**
     * 获取优惠券详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:coupon:query')")
    @GetMapping(value = "/{couponId}")
    public AjaxResult getInfo(@PathVariable("couponId") Long couponId)
    {
        return success(couponService.selectCouponByCouponId(couponId));
    }

    /**
     * 新增优惠券
     */
    @PreAuthorize("@ss.hasPermi('system:coupon:add')")
    @Log(title = "优惠券", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiImplicitParams({
                    @ApiImplicitParam(name = "createBy", value = "创建者", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "Date", dataTypeClass = Date.class),
                    @ApiImplicitParam(name = "updateBy", value = "更新者", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "Date", dataTypeClass = Date.class),
                    @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "name", value = "优惠券名称", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "need", value = "满足金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
                    @ApiImplicitParam(name = "derate", value = "优惠金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
                    @ApiImplicitParam(name = "timer", value = "有效期", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "couponType", value = "优惠卷类型", dataType = "Integer", dataTypeClass = Integer.class),
                    @ApiImplicitParam(name = "consumeAmount", value = "消费金额", dataType = "Integer", dataTypeClass = Integer.class),
    })
    public AjaxResult add(@RequestBody Coupon coupon)
    {
        return toAjax(couponService.insertCoupon(coupon));
    }

    /**
     * 修改优惠券
     */
    @PreAuthorize("@ss.hasPermi('system:coupon:edit')")
    @Log(title = "优惠券", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiImplicitParams({
                    @ApiImplicitParam(name = "createBy", value = "创建者", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "Date", dataTypeClass = Date.class),
                    @ApiImplicitParam(name = "updateBy", value = "更新者", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "Date", dataTypeClass = Date.class),
                    @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "name", value = "优惠券名称", dataType = "String", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "need", value = "满足金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
                    @ApiImplicitParam(name = "derate", value = "优惠金额", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
                    @ApiImplicitParam(name = "timer", value = "有效期", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult edit(@RequestBody Coupon coupon)
    {
        return toAjax(couponService.updateCoupon(coupon));
    }

    /**
     * 删除优惠券
     */
    @PreAuthorize("@ss.hasPermi('system:coupon:remove')")
    @Log(title = "优惠券", businessType = BusinessType.DELETE)
	@DeleteMapping("/{couponIds}")
    public AjaxResult remove(@PathVariable Long[] couponIds)
    {
        return toAjax(couponService.deleteCouponByCouponIds(couponIds));
    }

    /**
     * 获取优惠券下拉
     * @param couponId
     * @return
     */
    @DeleteMapping("/getCouponDropdown")
    public AjaxResult getCouponDropdown()
        {
            RegisterStatusEnum[] values = RegisterStatusEnum.values();
            List<RegisterStatus> list = new ArrayList<>();
            for (RegisterStatusEnum value : values) {
                RegisterStatus coupon = new RegisterStatus();
                coupon.setCode(value.getCode());
                coupon.setDesc(value.getDesc());
                list.add(coupon);
            }
            return success(list);
        }
}
